package com.espirit.eap.util.tagAdaptor;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.espirit.eap.pagelayout.Element;
import com.espirit.eap.pagelayout.Layout;
import com.espirit.eap.pagelayout.LinkTip;
import com.espirit.eap.pagelayout.PageCache;
import com.espirit.eap.pagelayout.TagInfo;

// TODO: Remove this class ? the TagSectionElementAdaptor can process it
@Service
public class TagLinkTipAdaptor implements TagElementAdaptor<LinkTip> {
	
	@Resource
	private TagAdaptorUtil tagAdaptorUtil;
	
	@Override
	public TagInfo getTagProperties(Layout root, LinkTip sectionElement, Map<String, Object> context) {
		TagInfo tagInfo = new TagInfo(true);
		tagInfo.setTagName("linkTip");
		Map<String, Object> properties = tagInfo.getTagProperties();
		LinkTip linkTip = sectionElement;
		
		properties.put("name", tagAdaptorUtil.getName(sectionElement));
		if (linkTip.getTarget() != null) {
			String target = linkTip.getTarget();
			properties.put("target", target);
		}
		properties.put("url", linkTip.getUrl());
		
		// extra properties
		Map<String, String> exProperties = sectionElement.getExProperties();
		if (exProperties != null) {
			properties.putAll(exProperties);
		}
		
		return tagInfo;
	}
	
	@Override
	public String getTagName(LinkTip element) {
		return "linkTip";
	}

	@Override
	public LinkTip updateToElement(Map<String, String> tagProperties, LinkTip existed, Map<String, Object> context, PageCache pageCache) {
		LinkTip pageReference = existed;
		String name = tagProperties.get("name");
		if (isNotEmpty(name)) {
			pageReference.setName(name);
		}
		String target = tagProperties.get("target");
		if (target != null) {
			pageReference.setTarget(target);
		} else {
			// TODO: show the warning message?
		}
		pageReference.setUrl(tagProperties.get("url"));
		
		// the other standard property
		Map<String, Object> defaultTagProperties = (Map<String, Object>) context.get(DEFAULT_TAG_PROP);
		tagAdaptorUtil.updateElement(tagProperties, defaultTagProperties, existed);
		
		return existed;
	}

	private boolean isNotEmpty(String value) {
		return value != null && value.length() > 0;
	}
	
	@Override
	public Element addElement(Element parent, String tagName, Map<String, Object> properties, PageCache pageCache) {
		// if the parent isn't container, use the parent's parent
		Integer index = pageCache.increaseMaxId();
		Layout root = pageCache.getLayout();
				
		LinkTip linkTip = new LinkTip();
		linkTip.setTagName("linkTip");
		linkTip.setId(-index);
		linkTip.setUrl("");
		
		// name
		String name = tagAdaptorUtil.createName(root, tagName);
		linkTip.setName(name);
		
		Element sectionElement = tagAdaptorUtil.createSectionElement(root, parent, linkTip);
		return sectionElement;
	}

	@Override
	public void deleteElement(Element parent, LinkTip existed, PageCache pageCache) {
	}
};